#!/usr/bin/ruby
# -*- ruby -*-
#
# http://www.reddit.com/r/dailyprogrammer/comments/11shra/10202012_challenge_105_easy_word_unscrambler/

require 'optparse'

dict = '/usr/share/dict/words'

OptionParser.new do |o|
    o.on("-d", "--dictionary=DICTIONARY", String) { |dict| }
end.parse!

# Implementation 1 - use a dictionary and pre-compute anagrams
#
# Implementation 2 - generate permutations of a word and see what permutations
#   are in a dictionary
implementation = :permutations

if implementation == :dictionary
    words = {}

    # Load up the dictionary - takes some time
    File.open(dict) do |f|
        while (word = f.gets) != nil
            word.strip!

            sorted_chars = word.downcase.split(//).sort.join("")

            words[sorted_chars] ||= []
            words[sorted_chars] << word
        end
    end

    # Unscramble words
    ARGV.each do |scrambled|
        sorted = scrambled.downcase.split(//).sort.join("")

        puts "#{scrambled} => #{(words[sorted] || []).join(", ")}"
    end
elsif implementation == :permutations
    def permutations(curr, word = "", coll = [])
        if curr.empty?
            coll << word
        else
            p = ""

            s = curr.split(//)

            until s.empty?
                c = s.shift

                permutations(p + s.join(""), word + c, coll)

                p += c
            end
        end

        return coll
    end

    ARGV.each do |word|
        p = permutations(word)

        matches = p.select do |per|
            system("fgrep -qi #{per} #{dict}")
        end

        puts "#{word} => #{matches.join(", ")}"
    end
end
